/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.nls.support;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.nothing.common.util.HttpUtils;
import org.vacoor.nothing.common.util.IOUtils;
import org.vacoor.nothing.security.nls.Translator;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Properties;

/**
 * @author vacoor
 */
public class YouDaoTickleTranslator extends TranslatorSupport {
    // no key
    public static final String API = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null";
    public static final Translator INSTANCE = new YouDaoTickleTranslator();

    @Override
    public boolean accepts(Locale from, Locale to) {
        return true;
    }

    @Override
    protected String doTranslate(String text, Locale from, Locale to, Properties props) {
        LOG.debug("执行有道翻译: {}, {} -> {}", text, from, to);
        try {
            HttpURLConnection conn = HttpUtils.createConnection(API);
            // warn 如果指定 contentType 头, contentType中不能包含 charset=

            HttpUtils.sendPostData(conn, ImmutableMap.<String, Object>builder()
                            .put("type", toTranslateDirection(from, to))
                            .put("doctype", "json")
                            .put("keyfrom", "fanyi.web")
                            .put("ue", "UTF-8")
                            .put("xmlVersion", "1.6")
                            .put("typoResult", true)
                            .put("i", text)
                            .build()
            );
            InputStream is = conn.getInputStream();
            String json = IOUtils.readText(is, Charsets.UTF_8, true);
            // {"type":"ZH_CN2EN","errorCode":0,"elapsedTime":1,"translateResult":[[{"src":"密码","tgt":"password"}]]}
//        JsonNode node = Jacksons.deserialize(is, JsonNode.class);
            JsonNode node = Jacksons.deserialize(json, JsonNode.class);
            String s = node.get("translateResult").get(0).get(0).get("tgt").asText();
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String toTranslateDirection(Locale from, Locale to) {
        return (from.toString() + "2" + to.toString()).toUpperCase();
    }
}
